import React, { Component } from "react";
import PropTypes from "prop-types";
import Cropper from "react-cropper"; // 引入Cropper
import "cropperjs/dist/cropper.css"; // 引入Cropper对应的css
import { Modal, message } from 'antd';
import "./ClassCropperModal.scss";
import { getData, GUID, getQueryVariable } from "../js/fetch";
import $ from 'jquery';
// import base64;
// import { ErrorAlert } from "../js/fetch/util";
const MAX_FILE_SIZE = 20 * 1024 * 1024; //文件最大限制为2MB
const BYTES_PER_SLICE = 3.9 * 1024 * 1024;
export default class ClassCropperModal extends Component {
  static propTypes = {
    // uploadedImageFile: PropTypes.object.isRequired,
    onClose: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    // onCheck: PropTypes.func.isRequired,
    Visiable: PropTypes.bool.isRequired,
    UpDataUrl: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
    console.log(props, 'props.baseUrl');
    this.state = {
      src: null,
      classModalVisible: props.Visiable,
      classModalFile: null,
      title: props.title ? props.title : "上传图片",
      bodyStyle: props.bodyStyle ? props.bodyStyle : {},
      filename: props.filename ? props.filename : "",
      baseUrl: props.baseUrl ? props.baseUrl : "http://192.168.129.1:30101", //图片上传基地址
      aspectRatio: props.aspectRatio ? props.aspectRatio : 1
    };
  }

  componentWillMount() {
    const fileReader = new FileReader();
    fileReader.onload = e => {
      const dataURL = e.target.result;
      this.setState({ src: dataURL });
    };
    if (this.state.classModalFile !== null) {
      fileReader.readAsDataURL(this.state.classModalFile);
    }
    // console.log(this.props.Visiable,'Visiable')
  }
  inputFileRef = React.createRef();
  componentDidUpdate(prevProps) {
    if (!prevProps.Visiable && this.props.Visiable) {
      // setTimeout(() => {
      //   if (this.inputFileRef.current) {
      //     this.inputFileRef.current.click();
      //   }
      // }, 0);
    }
  }

  handleSubmit = () => {
    console.log(312312312)
    if (this.state.classModalFile === null) {
      message.error('请先选择需要上传的图片~', 1.5);
      return false;
    }

    if (!this.state.submitting) {

      // let url = `/homepage_images` // 你要上传的url
      // 拿到文件名
      // let filename = this.props.uploadedImageFile.name
      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var canvas = this;
            setTimeout(function () {
              var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]);
              var len = binStr.length;
              var arr = new Uint8Array(len);
              for (var i = 0; i < len; i++) {
                arr[i] = binStr.charCodeAt(i);
              }
              console.log(arr, 'arr');
              callback(new Blob([arr], { type: type || 'image/png' }));
            });
          }
        });
      }
      // TODO: 这里可以尝试修改上传图片的尺寸
      this.cropper.getCroppedCanvas().toBlob(blob => {
        console.log(blob)
        let fileType = blob.type;
        console.log(fileType);
        this.setState({
          totalSize: blob.size,
          fileName: '图片',
          hasSendNum: 0,
          totalSlices: Math.ceil(blob.size / BYTES_PER_SLICE),
        })
        let slice = blob.slice(0, BYTES_PER_SLICE);//切割文件

        let imgDataUrl = this.cropper.getCroppedCanvas().toDataURL('image/jpeg')
        console.log(imgDataUrl)
        let base64Img = imgDataUrl // base64编码的图片
        let imgFile = this.dataURLtoFile(base64Img)
        this.uploadFile(blob, slice, this.state.hasSendNum + 1, this.state.classModalFile, fileType, imgFile);
      });
    }
  };
  //转换base64图片
  dataURLtoFile(dataurl, filename = this.state.filename ? this.state.filename : 'file') {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime
    })
  }

  getObjectURL(file) {
    var url = null
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }
    return url
  };

  uploadFile(blob, slice, index, file, fileType, imgFile, guid) {


    console.log('blob：', blob, 'slice:', slice, index, fileType, 'imgFile===>', imgFile,);
    let $this = this;
    if (!guid) {
      guid = new GUID().newGUID();
    }
    let formData = new FormData();
    formData.append("modelName", "images");
    formData.append("files", imgFile);
    $.ajax({
      url:
        sessionStorage.getItem('itemUrl') +
        'api/commons/file/batch/upload',
      type: 'POST',
      cache: false,
      data: formData,
      //dataType: 'json',
      //async: false,
      processData: false,
      contentType: false,
      headers: {
        'Authorization': getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
      .done(function (res) {
        if (res.code == 200) {
          console.log('reshhhhhhhhhhhhhhhhh',res);
          let imgUrl = res.data[0].url
          $this.props.onSubmit(imgUrl)
        }
        $this.setState({
          hasSendNum: $this.state.hasSendNum,
        }, () => {
          if (index == $this.state.totalSlices) {
          } else {
            // $this.setState({
            //   hasSendNum: $this.state.hasSendNum + 1
            // }, () => {
            //   // console.log(index);

            //   // console.log(index*BYTES_PER_SLICE);
            //   let end = index * BYTES_PER_SLICE + BYTES_PER_SLICE;
            //   if (index * BYTES_PER_SLICE + BYTES_PER_SLICE >= blob.size) {
            //     end = blob.size
            //   }
            //   // console.log(blob);
            //   slice = blob.slice(index * BYTES_PER_SLICE, end);
            //   index = index + 1;
            //   // $this.uploadFile(blob, slice, index, $this.state.classModalFile, fileType, imgFile)
            // })
          }
        })
      }).fail(function () {
        if (blob) {
          $this.setState({
            NewsTitleImg: '',
          })
        } else {
          $this.setState({
            AttachmentID: '',
            AttachmentUrl: '',
            AttachmentName: '',
            AttachmentSize: '',
            isupload: false,
          })
          message.error('上传失败~');
        }

      });
  }

  cancelSubmit = (NewsTitleImg) => {
    this.props.onClose(NewsTitleImg);
    this.setState({
      classModalFile: null
    });
  };

  handleClassFileChange = e => {
    const file = e.target.files[0];
    console.log(file)
    if (file) {
      if (file.size <= MAX_FILE_SIZE) {
        if (file.type !== 'image/png' && file.type !== 'image/jpeg' && file.type !== 'image/jpg') {
          message.error('请上传JPG/JPEG/PNG格式的图片~', 1.5);
          return;
        }
        this.setState(
          {
            classModalFile: file // 先把上传的文件暂存在state中
          },
          () => {
            const fileReader = new FileReader();
            fileReader.onload = e => {
              const dataURL = e.target.result;
              this.setState({ src: dataURL });
            };

            fileReader.readAsDataURL(this.state.classModalFile);
          }
        );
      } else {
        message.error('图片大小不能超过20M~', 1.5);
      }
    }
    // console.log(this.state.classModalFile);
  };

  render() {
    const { classModalFile } = this.state;

    return (
      <Modal
        ref="handleAdminMadal"
        bodyStyle={{
          height: "473px",
          padding: 0,
          ...this.state.bodyStyle
        }}
        type="1"
        width="781px"
        centered
        destroyOnClose={true}
        title={this.state.title}
        visible={this.props.Visiable}
        footer={null}
        onOk={this.handleSubmit}
        onCancel={this.cancelSubmit}
      >
        <div className="modal-panel">
          <div className="upload-tips" style={{ visibility: this.props.Visiable ? 'visible' : 'hidden' }}>
            <label className="btn choose-pic">
              <span className="inputBox">选择本地图片</span>
              <input
                type="file"
                style={{ display: "none" }}
                onChange={this.handleClassFileChange}
                accept="image/jpg,image/jpeg,image/png"
                className="btn choose-pic"
                ref={this.inputFileRef}
              />
            </label>
            上传要求：请上传JPG/JPEG/PNG格式的图片，图片大小不能超过20MB
          </div>
          {classModalFile === null ? <div className='updata-empty'><i></i><p>请上传本地图片</p></div> : <div className="cropper-container-container">
            <div
              className={`cropper-container ${classModalFile === null ? "default" : ""
                }`}
            >
              {classModalFile !== null ? (
                <div>
                  <Cropper
                    src={this.state.src}
                    className="cropper"
                    ref={cropper => (this.cropper = cropper)}
                    // Cropper.js options
                    viewMode={1}
                    zoomable={true}
                    aspectRatio={this.state.aspectRatio} // 固定为1:1  可以自己设置比例, 默认情况为自由比例
                    guides={true}
                    preview=".cropper-preview"
                    movable={true}
                    rotatable={false}
                    // zoomOnTouch={true}
                    // cropBoxMovable={true}
                    center={true}
                    highlight={true}
                    modal={false}
                    rotateTo={-90}
                  // scalable={true}
                  // toggleDragModeOnDblclick={true}
                  // moveTo={true}
                  // zoomOnWheel={true}
                  // responsive={true}
                  // background={false}
                  />
                  {/* <img src={this.state.src} alt='图片错误' /> */}
                  <p className="tips-p">提示: 请拖动窗口裁剪图片</p>
                </div>) : (
                ""
              )}
            </div>

            <div className="preview-container default">
              <p className="tips-p2">裁剪效果图</p>
              {classModalFile !== null ? (
                <div className="cropper-preview"></div>
              ) : (
                ""
              )}
            </div>
          </div>}
          <div className="group-btn">
            <div className="cancel-btn" onClick={this.cancelSubmit}>取消</div>
            <div className="confirm-btn" onClick={this.handleSubmit}>确定</div>

          </div>
        </div>
      </Modal>
    );
  }
}
